package com.ivan.servlet;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: ivan
 * Date: 12-6-19
 * Time: 下午2:01
 * To change this template use File | Settings | File Templates.
 */
public class MultiFileUploadController extends MultiActionController {

    public MultiFileUploadController(){

    }

//    private String RESOURCE_NAME = getServletContext().getRealPath("/fileUpload");
    private String RESOURCE_NAME = "d:/";

    private MultiFileEntity bindMultiFileEntity(HttpServletRequest request){
        MultiFileEntity fileEntity = new MultiFileEntity();
        ServletRequestDataBinder binder = new ServletRequestDataBinder(fileEntity);
        binder.bind(request);
        return  fileEntity;
    }

    private void uploadFile(MultiFileEntity fileEntity) throws IOException{
        if(fileEntity == null)
            return;
        MultipartFile multipartFile = fileEntity.getFile();
        String fileName = multipartFile.getOriginalFilename();
        String extName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String resultName = System.currentTimeMillis() + extName;

        String filePath = RESOURCE_NAME+"/"+resultName;
        FileCopyUtils.copy(multipartFile.getBytes(),new File(filePath));

    }

    public ModelAndView uploadFile(HttpServletRequest request,HttpServletResponse response){
        MultiFileEntity file = bindMultiFileEntity(request);
        try {
            uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return null;
    }
}
